package hoang.hut.app.network;

import hoang.hut.app.info.WebserviceConfig;
import hoang.hut.app.ui.BaseActivity;
import hoang.hut.libs.R;

import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

public class AsyncHttpResponseProcess implements AsyncHttpResponseListener {

	private BaseActivity baseActivity; 

	private boolean isShowDialog = true; 

	public AsyncHttpResponseProcess(BaseActivity activity) {
		this.baseActivity = activity;
	}

	public AsyncHttpResponseProcess(BaseActivity activity, boolean isShow) {
		this.baseActivity = activity;
		this.isShowDialog = isShow;
	}

	@Override
	public void before() {
		if (isShowDialog) {
			baseActivity.showProgressDialog();
		}
	}

	@Override
	public void after(int statusCode, HttpResponse response) {
		if (isShowDialog) {
			baseActivity.closeProgressDialog();
		}

		switch (statusCode) {
		case AsyncHttpBase.NETWORK_STATUS_OFF:
			baseActivity.showCustomPositiveDialog(baseActivity, R.string.dialog_title_error, 
					R.string.message_network_is_unavailable, R.drawable.button_ok);
			break;

		case AsyncHttpBase.NETWORK_STATUS_ERROR:
			baseActivity.showCustomPositiveDialog(baseActivity, R.string.dialog_title_error, 
					R.string.message_network_error, R.drawable.button_ok);
			break;
		case AsyncHttpBase.NETWORK_EXCEPTION:
			baseActivity.showCustomPositiveDialog(baseActivity, R.string.dialog_title_error, 
					R.string.message_server_error, R.drawable.button_ok);
			break;
		case AsyncHttpBase.NETWORK_STATUS_TIMEOUT:
			baseActivity.showCustomPositiveDialog(baseActivity, R.string.dialog_title_error, 
					R.string.message_request_time_out, R.drawable.button_ok);
			break;
			
		case AsyncHttpBase.NETWORK_STATUS_OK:
			processHttpResponse(response);
			break;
		default:
			break;
		}

	}

	/**
	 * ham xu ly response thanh cong lay json, xu ly json
	 * 
	 * @param response
	 */
	private void processHttpResponse(HttpResponse response) {
		String jsonString = "";
		try {
			jsonString = EntityUtils.toString(response.getEntity());
			if(jsonString==null){
				baseActivity.showCustomPositiveDialog(baseActivity, R.string.dialog_title_error, 
						R.string.message_error_cant_extract_server_response, R.drawable.button_ok);
				return;
			}else{
				int success = 0; 
				JSONObject jsonObject = new JSONObject(jsonString);
				success = jsonObject.getInt(WebserviceConfig.KEY_SUCCESS);
				if(success==1){
					processIfResponseSuccess(jsonObject);
				}else{
					processIfResponseFail();
				}
			}
		} catch (Exception e) {
		}
	}
	/**
	 * phuong thuc xu ly du lieu khi thanh cong
	 * @param json
	 */
	public void processIfResponseSuccess(JSONObject json){
		
	}
	/**
	 * xu ly xu lieu khi that bai
	 */
	public void processIfResponseFail(){
		
	}
}
